package com.ruoyi.core.util;

import com.ruoyi.core.exception.RunException;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * @author wanghao 913351190@qq.com
 * @create 2022/3/30 14:09
 */
public abstract class DownloadFileUtil {

    /**
     * 下载文件流
     *
     * @param response HttpServletResponse
     * @param file     要下载的文件对象
     * @param filename 下载的文件名
     */
    public static void download(HttpServletResponse response, File file, String filename) {

        try {
            //文件名
            if (filename == null || filename.length() == 0) {
                filename = file.getName();
            }

            try (InputStream inputStream = new FileInputStream(file)) {

                response.reset();
                //response.addHeader("Access-Control-Allow-Origin", "*");//默认不允许跨域
                response.setContentType("application/octet-stream");
                //纯下载方式 文件名应该编码成UTF-8
                response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
                response.addHeader("Content-Length", "" + inputStream.available());

                byte[] buffer = new byte[1024];
                int len;
                OutputStream outputStream = response.getOutputStream();
                while ((len = inputStream.read(buffer)) > 0) {
                    outputStream.write(buffer, 0, len);
                }
            }
        } catch (Exception e) {
            throw new RunException("下载文件" + file.getAbsolutePath() + "异常" + e.getMessage(), e);
        }

    }

    /**
     * 下载文件流
     *
     * @param file     要下载的文件对象
     * @param filename 下载的文件名
     */
    public static void download(File file, String filename) {

        download(RequestContextUtil.getResponse(), file, filename);

    }

    /**
     * 下载文件流
     *
     * @param file 要下载的文件对象
     */
    public static void download(File file) {

        download(RequestContextUtil.getResponse(), file, file.getName());

    }

}
